# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings
from common.channel import admin_db as channel_admin_db

from async import async_job
from common.agentpay.base import AbstractHandler
from common.agentpay.db import get_agent_pay_order
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.types import Enum
from common.agentpay.model import AGENT_PAY_STATUS

_LOGGER = track_logging.getLogger(__name__)

IP = '39.104.98.218'

APP_CONF = {
    'W20190118001': {  # Me支付 支付宝2.5% 50-3000 dwc
        'API_KEY': 'B4BBD787C5567AB5530ECBD60BB08E66',
        'gateway': 'http://39.104.98.218/pay/unifiedorder',
        'query_gateway': 'http://39.104.98.218/pay/orderquery',
        'create_agent_pay': 'http://{}/agentpay/unifiedorder'.format(IP),
        'query_agent_pay': 'http://{}/agentpay/orderquery'.format(IP),
        'query_balance': 'http://{}/agentpay/amountquery'.format(IP)
    },
}

NOTIFY_PAY_STATUS = Enum({
    "WAIT": (0, u"等待"),
    "SUCCESS": (1, u"成功"),
    "FAIL": (2, u"失败"),

})


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_create_agent_pay(mch_id):
    return APP_CONF[mch_id]['create_agent_pay']


def _get_query_agent_pay(mch_id):
    return APP_CONF[mch_id]['query_agent_pay']


def _get_query_balance(mch_id):
    return APP_CONF[mch_id]['query_balance']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k]:
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("mepay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _get_pay_type(service):
    if service == 'alipay_scan':
        return 'ALI_QR_CODE'
    elif service == 'wechat_scan':
        return 'WX_QR_CODE'
    elif service == 'wechath5':
        return 'WX_H5'
    elif service == 'alipayh5':
        return 'ALI_H5'
    return 'ALI_H5'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)

    parameter_dict = OrderedDict((
        ('version', '1.0'),
        ('sign_type', 'MD5'),
        ('mch_id', str(app_id)),
        ('out_order_no', str(pay.id)),
        ('pay_type', str(_get_pay_type(service))),
        ('total_fee', str(int(pay_amount * 100))),
        ('body', 'MePay'),
        ('return_url', '{}/pay/api/{}/mepay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('notify_url', '{}/pay/api/{}/mepay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("mepay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['out_order_no'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=3, verify=False)
    _LOGGER.info("mepay create rsp: %s, order_id is: %s", response.text, json.loads(response.text)['out_order_no'])
    extend = json.loads(pay.extend or '{}')
    extend.update({'pay_type': parameter_dict['pay_type']})
    order_db.fill_extend(pay.id, extend)
    return {'charge_info': json.loads(response.text)['pay_url']}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = json.loads(request.body)
    _LOGGER.info("mepay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['out_order_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('mepay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['pay_status'])
    trade_no = ''
    if 'pay_fee' in data.keys():
        total_fee = float(data['pay_fee']) / 100.0
    else:
        total_fee = float(pay.total_fee)
    pay_type = json.loads(pay.extend or '{}').get('pay_type', 0)
    extend = {
        'pay_type': pay_type,
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 0 - 未支付; 1 - 支付成功; 2 - 支付失败
    if trade_status == '1':
        _LOGGER.info('mepay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    pay_type = json.loads(pay_order.extend or '{}').get('pay_type', 0)
    parameter_dict = OrderedDict((
        ('version', '1.0'),
        ('sign_type', 'MD5'),
        ('mch_id', app_id),
        ('out_order_no', str(pay_order.id)),
        ('pay_type', pay_type),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info('mepay query data: %s, order_id is: %s', json.dumps(parameter_dict), parameter_dict['out_order_no'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3, verify=False)
    _LOGGER.info('mepay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['pay_status'])
        if 'pay_fee' in data.keys():
            total_fee = float(data['pay_fee']) / 100.0
        else:
            total_fee = float(pay_order.total_fee)
        trade_no = ''
        extend = {
            'pay_type': pay_type,
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }
        # 0 - 未支付; 1 - 支付成功; 2 - 支付失败
        if trade_status == '1':
            _LOGGER.info('mepay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)


class MePayHandler(AbstractHandler):

    def submit_order(self, order_no):
        """
        创建代付请求
        :return:
        """
        agent_pay = get_agent_pay_order(order_no)
        chn = channel_admin_db.get_channel(int(agent_pay.channel_id))

        chn_info = json.loads(chn.info)

        notify_url = '{}/pay/api/{}/mepay/'.format(
            settings.NOTIFY_PREFIX, settings.AGENT_PAY_NOTIFY_PATH)
        params = {
            'version': '1.0',
            'sign_type': 'MD5',
            'mch_id': (chn_info['app_id']),
            'out_order_no': agent_pay.order_no,
            'total_fee': int(agent_pay.total_fee),
            'bank_code': agent_pay.bank_code,
            'card_no': agent_pay.card_no,
            'account_name': agent_pay.account_name,
            'phone_number': agent_pay.phone_number,
            'bank_name': agent_pay.bank_name,
            'notify_url': notify_url,
        }
        params['sign'] = generate_sign(params, _get_api_key(chn_info['app_id']))
        _LOGGER.info(u"me pay  create pay agent order params {}".format(params))
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}

        response = requests.post(_get_create_agent_pay(chn_info['app_id']), data=params, headers=headers, timeout=5,
                                 verify=False)
        _LOGGER.info("me pay  create pay agent order : %s", response.text.encode('utf8'))
        if response.status_code != 200:
            raise ParamError('mepay submit_order error')
        data = json.loads(response.text)
        ret_code = int(data.get('ret_code'))
        if ret_code:
            raise ParamError('mepay submit_order error %s ' % data.get('ret_msg'))

        return data.get('out_order_no'), notify_url

    def query_agent_pay(self, order_no):
        """
        查询代付请求
        :return:
        """
        agent_pay = get_agent_pay_order(order_no)
        chn = channel_admin_db.get_channel(int(agent_pay.channel_id))
        chn_info = json.loads(chn.info)
        params = {
            'version': '1.0',
            'sign_type': 'MD5',
            'mch_id': (chn_info['app_id']),
            'out_order_no': agent_pay.order_no,

        }
        params['sign'] = generate_sign(params, _get_api_key(chn_info['app_id']))

        _LOGGER.info(u"me pay  query_agent_pay  params {}".format(params))
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        response = requests.post(_get_query_agent_pay(chn_info['app_id']), data=params, headers=headers, timeout=5,
                                 verify=False)
        _LOGGER.info("me payquery_agent_pay : %s", response.text.encode('utf8'))
        if response.status_code != 200:
            raise ParamError('mepay query_agent_pay error')
        data = json.loads(response.text)
        ret_code = int(data.get('ret_code'))
        if ret_code:
            raise ParamError('mepay query_agent_pay error %s' % data.get('ret_msg'))
        return data.get('pay_status')

    def convert_notify_status(self, status):
        if status == NOTIFY_PAY_STATUS.SUCCESS:
            return AGENT_PAY_STATUS.SUCCESS
        elif status == NOTIFY_PAY_STATUS.FAIL:
            return AGENT_PAY_STATUS.FAIL
        elif status == NOTIFY_PAY_STATUS.WAIT:
            return AGENT_PAY_STATUS.SUBMIT

    def agent_pay_notify(self, order_no, status, pay_fee):
        """
        代付到账回调
        :return:
        """
        order = get_agent_pay_order(order_no)
        assert status in (NOTIFY_PAY_STATUS.SUCCESS, NOTIFY_PAY_STATUS.FAIL)
        status = self.convert_notify_status(status)
        self.agent_pay_callback(order_no, status)

    def query_balance(self, mch_id):
        """
        查询余额,返回单位分
        :return:
        """
        params = {
            'version': '1.0',
            'sign_type': 'MD5',
            'mch_id': mch_id,

        }
        params['sign'] = generate_sign(params, _get_api_key(mch_id))
        _LOGGER.info(u"me pay  query_agent_pay  params {}".format(params))
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        response = requests.post(_get_query_balance(mch_id), data=params, headers=headers, timeout=5,
                                 verify=False)
        _LOGGER.info("me payquery_agent_pay : %s", response.text.encode('utf8'))
        if response.status_code != 200:
            raise ParamError('mepay query_balance error')
        data = json.loads(response.text)
        ret_code = int(data.get('ret_code'))
        if ret_code:
            raise ParamError('mepay query_agent_pay error %s' % data.get('ret_msg'))
        return data.get('amount')


handler = MePayHandler()
